<template>
	<view class="Index">
		<cc-scrollTag @tabChange="tabChange" :tagsList="titles" bgColor="#FA436A"></cc-scrollTag>
		<view class="content">
			<scroll-view scroll-y="true">
				<view style="margin: 10rpx 0;">
					<!-- 横幅广告 -->
					<ad v-if="showad" :unit-id="config.BannerID"></ad>
				</view>
				<!-- <image :src="giteeUrl + 'static/gzh.webp'" :mode="widthFix" show-menu-by-longpress="true"
					style="width: 100%; height: auto; flex-shrink: 0;"></image> -->
				<view v-if="hint != null && hint != '' && globalAd == true" class="hint">
					{{ hint }}
				</view>
				<view style="min-height: 90vh;">
					<scroll-view>
						<view style="display: flex; flex-direction: row; flex-wrap: wrap;width: 100vw">
							<view v-for="(item, index) in datas[page]" style="width: max-content">
								<view v-if="item != null" style="box-sizing: border-box; width: 50vw;" :key="index">
									<view class="item">
										<uv-image :src="item.image" mode="aspectFit" width="100%" height="281rpx"
											@click="jmppage(item)" :lazy-load="true"></uv-image>
										<uv-text :lines="1" :text="item.title" @click="jmppage(item)"
											customStyle="font-size: 30rpx;color: black; max-height: 45rpx"></uv-text>
										<uv-text :lines="2" :text="item.desc" @click="jmppage(item)"
											customStyle="font-size: 24rpx;color: #666; height: 70rpx;"></uv-text>
										<view class="btn">
											<uv-button v-if="item.ad == true" type="success" plain style="height: 2rem;"
												@click="getDownload(datas[page][index])">{{downloadtext}}{{page? '>' :""}}</uv-button>
											<uv-button v-else @click="openAD(datas[page][index])" type="primary" plain
												style="height: 2rem;">{{adbtntext}}{{item.page? '>' :""}}</uv-button>
										</view>
									</view>
								</view>
								<view v-else style="width: 100vw;">
									<view style="margin: 10rpx;">
										<ad v-if="showad" :unit-id="config.FullVideoID" ad-type="video"
											ad-theme="white"></ad>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<view style="margin: 50rpx 10rpx 10rpx 10rpx;"
					v-if="datas[page]!=null && datas[page].length < skipitem">
					<ad v-if="showad" :unit-id="config.FullVideoID" ad-type="video" ad-theme="white"></ad>
				</view>

			</scroll-view>
		</view>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		onMounted
	} from 'vue';
	import tools from "../../utils/tools.js";
	import gdatas from "../../utils/data.js";
	import config from '../../common/config.js';

	const column = ref(2);
	const datas = ref([]);
	let titles = ref([]);
	let datadir = "./";
	let page = ref(0)
	let encryptions = [];
	let hint = "";
	let globalAd = ref(false);
	let showad = ref(false)
	let skipitem = ref(8)

	let interstitialAd = null;
	let isInterstitialLoading = false;
	let rewardedVideoAd = null;
	let isVideoAdLoading = false;
	let selectItem = null;
	let toast = ref(null)
	let adbtntext = ref("看广告获取资源链接")
	let downloadtext = ref("点击获取资源链接")
	let adcallback = {
		a: 100,
		b: "200",
	}

	//修改成自己的码云数据地址
	const giteeUrl = ref(config.giteeUrl);

	//页面加载时执行
	onMounted(() => {

		//插屏广告实例
		if (wx.createInterstitialAd) {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: config.InterstitialID
			})
			interstitialAd.onLoad(() => {
				if (interstitialAd && !isInterstitialLoading) {
					isInterstitialLoading = true
					interstitialAd.show().catch((err) => {
						console.error('插屏广告显示失败', err)
					})
				}
			})
			interstitialAd.onError((err) => {
				console.error('插屏广告加载失败', err)
			})
			interstitialAd.onClose(() => {
				console.log('插屏广告关闭')
			})
		}

		//激励广告
		if (wx.createRewardedVideoAd) {
			rewardedVideoAd = wx.createRewardedVideoAd({
				adUnitId: config.RewardedVideoID
			})
			rewardedVideoAd.onLoad(() => {
				console.log('激励广告加载成功');
				isVideoAdLoading = true
			})
			rewardedVideoAd.onError((e) => {
				console.error('激励视频广告加载失败', e)
				showToast({
					type: 'default',
					message: e,
				})
			})
			rewardedVideoAd.onClose((e) => {
				// 用户点击了关闭广告
				console.log("激励广告关闭", e);
				if (e && e.isEnded) {
					selectItem.ad = true;
					getlink(selectItem)
				} else {
					showToast({
						type: 'default',
						message: '激励广告未观看完成',
					})
				}
			})
		}
		showad.value = true


		//动态调整列数
		uni.getSystemInfo({
			success: function(res) {
				column.value = parseInt(res.windowWidth / 250);
				if (column.value == 0) {
					column.value = 1
				}
			}
		})
		//动态调整列数
		uni.onWindowResize((res) => {
			column.value = parseInt(res.size.windowWidth / 250);
			if (column.value == 0) {
				column.value = 1
			}
		})

		//获取数据
		gettitles();
	})

	function showToast(params) {
		toast.value.show({
			...params,
			complete() {}
		})
	}

	function imageClick(item) {
		jmppage(item)
		// uni.previewImage({
		// 	urls: [item.image],
		// 	current: '',
		// 	success: function(res) {},
		// 	fail: function(res) {},
		// 	complete: function(res) {},
		// })
	}

	function loaded() {
		console.log('加载完成')
	}

	//打开广告观看，暂时不支持广告
	function openAD(item) {
		selectItem = item;
		if (item.page != null && item.page != "") {
			jmppage(item);
			return
		}
		showVideoAd();
	}

	//获取资源链接
	function getDownload(item) {
		selectItem = item;
		if (item.page != null && item.page != "") {
			jmppage(item);
			return
		}
		getlink(item)
	}

	function getlink(item) {
		let data = item.link;
		//判断数据中的encryption是否位true,如果加密就解密
		if (encryptions[page.value] == true) {
			//后面为16位的密钥和16位的向量，百度搜索aes cbc加密工具可以对数据中的link进行加密
			data = tools.Decrypt(data, config.passwd, config.iv);
		}
		//复制到粘贴板
		uni.setClipboardData({
			data: data,
		})
	}

	function gettitles() {
		//从码云读取数据
		uni.request({
			url: giteeUrl.value + "index.dat",
			success: (res) => {
				hint = res.data.hint;
				globalAd.value = res.data.globalad;
				datadir = res.data.datadir;
				let keys = res.data.titles;
				titles.value = keys;
				let itemdatas = [];
				encryptions = [];
				adbtntext.value = res.data.adbtntext;
				downloadtext.value = res.data.downloadtext;
				if (res.data.skipitem != null) {
					skipitem.value = res.data.skipitem
				}
				for (let idx in keys) {
					encryptions.push(false)
					itemdatas.push([])
				}
				datas.value = itemdatas;
				getlist(0);
			}
		})
	}

	function tabChange(res) {
		page.value = res;
		getlist(res);
	}

	function jmppage(item) {
		if (item.page == null) return;
		gdatas.pageUrl = item.page;
		gdatas.linkUrl = item.link;
		gdatas.encryption = encryptions[page.value];
		gdatas.item = item;
		gdatas.hint = hint;
		gdatas.globalAd = globalAd.value;
		gdatas.adbtntext = adbtntext.value;
		gdatas.downloadtext = downloadtext.value;
		uni.navigateTo({
			url: `/pages/details/details`
		});
	}

	function getlist(ikey) {
		if (datas.value[ikey].length != 0) return;
		uni.request({
			url: giteeUrl.value + datadir + "/" + titles.value[ikey] + ".dat",
			success: (res) => {
				let jsondatas = res.data.list;
				let itemdatas = [];
				encryptions[ikey] = res.data.encryption;
				for (let idx in jsondatas) {
					let data = jsondatas[idx];
					let url = data.image;
					data.ad = !data.ad;
					if (url.substr(0, 4) != "http") {
						data.image = giteeUrl.value + data.image
					}

					//插入视频广告
					if (idx % skipitem.value == 0 && idx != 0) {
						itemdatas.push(null)
					}
					itemdatas.push(data)
				}
				datas.value[ikey] = itemdatas;
			}
		})

	}

	function showVideoAd() {
		if (isVideoAdLoading) {
			isVideoAdLoading = false;
			rewardedVideoAd.show();
		} else {
			showToast({
				type: 'default',
				title: '激励广告未加载完成',
				message: "激励广告未加载完成",
			})
		}
	}
</script>

<style>
	page {
		display: flex;
		width: 100%;
		height: 100%;
		background-color: #f2f5f9;
	}
</style>
<style lang="scss" scoped>
	.Index {
		display: flex;
		flex-direction: column;
		height: 100%;
		width: 100%;
		overflow: hidden;
	}

	.content {
		display: flex;
		flex-grow: 1;
		overflow: hidden;
		// margin: auto 10rpx;
	}

	.custom-waterfalls-flow {
		// padding: 0 10rpx;
	}

	.hint {
		font-size: 0.8rem;
		color: #666;
		width: 100%;
		text-align: center;
	}

	.item {
		margin: 3rpx;
		padding: 10rpx;
		background-color: white;

		.title {
			line-height: 48rpx;
			font-size: 28rpx;
			color: #222;
		}

		.desc {
			font-size: 24rpx;
			color: #666;
		}

		.btn {
			margin: 10px 2px 2px 2px;
		}
	}
</style>